package filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpSession session = ((HttpServletRequest)servletRequest).getSession();
        String requestPath =  ((HttpServletRequest)servletRequest).getServletPath();

        if(session.getAttribute("uName") != null ||
                requestPath.endsWith("index.jsp") || requestPath.endsWith("LoginServlet") ||
                requestPath.endsWith("regist.jsp.jsp") || requestPath.endsWith("RegistServlet"))
            // pass the request along the filter chain
            filterChain.doFilter(servletRequest, servletResponse);
        else {
            servletRequest.setAttribute("filterMess", "你还没登录呢！请先登录！");
            servletRequest.getRequestDispatcher("login.jsp").forward(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
